<?php
  include('../includes.php');
  $membership = New Membership();
  $membership->confirm_admin();

  $action  = $_POST['action'];
  $datum   = explode('/', $_POST['datum']);
  $dag     = $datum[0];
  $week    = $datum[1];
  $jaar    = $datum[2];
  $tijd    = $_POST['tijd'];
  $les_id  = $_POST['les'];

  $id = $_POST['keuze'];

  if ($id != "Selecteer Iemand")
  {
    if ($action === "aanmelden")
      mysql_query('INSERT INTO '.DB_DEELNEMER.' (les_ID, user_ID) VALUES ("'.$les_id.'", "'.$id.'")');
    else if ($action === "afmelden")
    {
      $current_day  = date('j');
      $current_week = Website::week_format(date('W'));
      $current_time = date('H:i');

      /* Haal het ID op van diegene die als eerst gereserveerd heeft */
      $query = mysql_query('SELECT user_ID, MIN(counter) FROM '.DB_RESERVERING.' WHERE les_ID="'.$les_id.'" GROUP BY les_ID');
      $row   = mysql_fetch_assoc($query);

      $counter = $row['MIN(counter)'];
      $reserve_id = $row['user_ID']; 

      mysql_query('DELETE FROM '.DB_DEELNEMER.' WHERE les_ID="'.$les_id.'" AND user_ID="'.$id.'"');
      mysql_query('INSERT INTO '.DB_AFMELDING.' (les_ID, user_ID, afmeld_dag, week, afmeld_tijd) VALUES ("'.$les_id.'", "'.$id.'", "'.$current_day.'", "'.$current_week.'", "'.$current_time.'")');

      if ($counter > 0)
      {
        $do = mysql_query('INSERT INTO '.DB_DEELNEMER.' (les_ID, user_ID) VALUES ("'.$les_id.'", "'.$reserve_id.'")');

        if ($do)
        {
          //Reservering::send_note($les_id, $reserve_id);
          mysql_query('DELETE FROM '.DB_RESERVERING.' WHERE les_ID="'.$les_id.'" AND user_ID="'.$reserve_id.'"');
        }
      }
    }
    else if ($action === "reserve")
    {
      $aantal = Reservering::count_reservering_per_dag($dag, $week, $jaar, $tijd);

      if ($aantal < 3)
      {
        $query = mysql_query('SELECT MAX(counter) FROM '.DB_RESERVERING.' WHERE les_ID="'.$les_id.'"');
        $row   = mysql_fetch_assoc($query);
        
        $counter = $row['MAX(counter)'] + 1;

        mysql_query('INSERT INTO '.DB_RESERVERING.' (les_ID, user_ID, counter) VALUES ("'.$les_id.'", "'.$id.'", "'.$counter.'")');
      }
    }
    else if ($action === "reserve_afmelden")
      mysql_query('DELETE FROM '.DB_RESERVERING.' WHERE les_ID="'.$les_id.'" AND user_ID="'.$id.'"');
  }

  $url = BASE_URL;
  header("Location: $url/view/admin.php?d=$dag/$week/$jaar&t=$tijd");
?>